import { createStore } from 'vuex'
/* 引入api */
import {
  loginInfo, getUsersInfo, booksinfo, categoryInfo,
  addCategoryInfo,
  updateCategoryInfo, deleteCategoryInfo, addBookInfo,
  deleteBookInfo, updateBookInfor, bookLendInfo, addOrEditUserInfo, deleteUserInfo, getBorrowBookInfo, forgetPswOrEnrollAdminInfo, userBorrowBookInfo
} from "@/api/API";

export default createStore({
  state: {
    token: JSON.parse(sessionStorage.getItem('TOKEN')) || '',
    id: JSON.parse(sessionStorage.getItem('ID')) || '',
    flag: '1' //切换导航以及路由
  },
  getters: {
  },
  mutations: {
    LOGIN(state, { token, id }) {
      state.token = token;
      state.id = id;
    },

    //退出登录 删除数据
    DELETELOGINSTATE(state) {
      state.token = '';
      state.id = '';
    },
    //导航路由切换
    UPDATENAV(state, data) {
      state.flag = data;
    }
  },
  actions: {
    //请求登录
    async Login({ commit }, data) {
      let result = await loginInfo(data);
      if (result.status == 'success') {
        //存储token与状态
        commit('LOGIN', { token: result.data.account || '', id: result.data.id || '' });
        return result.status;
      }
    },

    //获取类别
    async getCategory() {
      let result = await categoryInfo();
      if (result.status == 'success') {
        return result || {};
      }
    },

    //添加类别
    async AddCategory({ commit }, data) {
      return await addCategoryInfo(data) || {};
    },

    //编辑类别
    async UpdateCategory({ commit }, data) {
      return await updateCategoryInfo(data) || {};
    },

    //获取书籍
    async getBooks({ }, { flag, cgName = "" }) {
      let result = await booksinfo(flag, cgName);
      if (result.status == 'success') {
        return result || {};
      }
    },

    //获取用户
    async getUsers({ }, { id, flag }) {
      return await getUsersInfo(id, flag) || {};
    },

    //删除指定类别
    async deleteCg({ }, { id, cg }) {
      return await deleteCategoryInfo(id, cg) || {};
    },
    //添加书籍
    async AddBook({ }, data) {
      return await addBookInfo(data) || {};
    },
    //删除书籍
    async DeleteBook({ }, id) {
      return await deleteBookInfo(id) || {};
    },
    //修改书籍信息
    async UpdateBookInfo({ }, data) {
      return await updateBookInfor(data) || {};
    },
    //借阅管理
    async getBookLend({ }, data) {
      return await bookLendInfo(data) || {};
    },
    //添加或编辑用户
    async AddOrEditUser({ }, data) {
      return await addOrEditUserInfo(data) || {};
    },
    //删除用户
    async DeleteUser({ }, id) {
      return await deleteUserInfo(id) || {};
    },
    //获取借阅书籍
    async GetBorrowBook({ }, id) {
      return await getBorrowBookInfo(id) || {};
    },
    //忘记密码 或 注册
    async ForgetPswOrEnrollAdmin({ }, data) {
      return await forgetPswOrEnrollAdminInfo(data) || {};
    },
    //用户借阅、归还书籍
    async UserBorrowBook({ }, data) {
      return await userBorrowBookInfo(data) || {};
    },
  },
  modules: {

  }
})
